from flask import Flask, request
from ledvr import get_db, reload_db, get_qa_chain
import os, json

db = get_db()
qa_chain = get_qa_chain()
app = Flask(__name__, static_folder='./html')


@app.route('/q')
def q():
    query = request.args.get('query')
    print("received query: {}".format(query))
    # docs = search(query)
    response = qa_chain.invoke(query)
    print("answer query: {}\nresponse:{}".format(query, json.dumps(response, ensure_ascii=False)))
    # return json.dumps(response, ensure_ascii=False, indent=4)
    return response


@app.route('/upload', methods=['POST', 'GET'])
def upload():
    f = request.files['file']
    basepath = os.path.dirname(__file__)
    upload_path = os.path.join(basepath, 'data', f.filename)
    f.save(upload_path)
    print('uploading ...')

    reload_db()
    global db
    db = get_db()
    return "success"


if __name__ == '__main__':
    app.run(threaded=True)
